import express from 'express';
import redis from '../db/cache.js';
import {
  addQuestion,
  badQuestionReputation,
  deleteQuestion,
  editQuestion,
  goodQuestionReputation,
  queryHotQuestionByTag,
  queryQuesitonByUsertag,
  queryQuestionByDate,
  queryQuestionByDateline,
  queryQuestionById,
  queryQuestionByKeyword,
  queryQuestionByTag,
  queryQuestionByUser,
  questionViewCountUp,
  recommendQuestions,
  searchIdea,
} from '../service/question.js';
import { deleteAnswerBySubordinate } from '../service/answer.js';

const questionRouter = express.Router();

questionRouter.post('/quiz', async (req, res) => {
  if (req.body.title.replace(/\s+/g, '') !== '' && req.body.detail.replace(/\s+/g, '') !== '' && req.body.tags.length > 0) {
    let tags;
    if (req.body.tags.length) {
      tags = req.body.tags.join(',');
    }
    const questionInfo = {
      question_title: req.body.title,
      question_detail: req.body.detail,
      question_tags: tags || null,
      question_img: req.body.imgPath || null,
      question_creator: Number(await redis.get(req.headers.authorization)),
      create_time: new Date().toLocaleString(),
    };

    addQuestion(questionInfo)
      .then(() => {
        res.send({ resCode: 200, message: '提问成功！' });
      })
      .catch((err) => {
        console.log(err);
        res.send({ resCode: 500, message: '提问接口异常' });
      });
  } else {
    res.send({ resCode: 500, message: '参数错误' });
  }
});

questionRouter.get('/recommendQuestions', async (req, res) => {
  const { user_prefer } = req.query;
  const result = [];
  if (user_prefer.length > 0) {
    for (const tag of user_prefer) {
      const [data, meta] = await recommendQuestions(tag);
      result.push(...data);
    }
    result.forEach((item) => {
      if (item.question_tags) {
        item.question_tags = item.question_tags.split(',');
      }
    });
    res.send({
      resCode: 200,
      data: result,
    });
  }
});

questionRouter.get('/searchIdea', (req, res) => {
  const { keyword } = req.query;
  if (keyword.replace(/\s+/g, '') === '') {
    res.send({ resCode: 500, message: '无意义的参数' });
  } else {
    searchIdea(keyword)
      .then((data) => {
        res.send({ resCode: 200, data });
      })
      .catch((err) => {
        console.log(err);
        res.send({ resCode: 500, message: '查询失败' });
      });
  }
});

questionRouter.get('/queryQuestionByTag', async (req, res) => {
  const questions = await queryQuestionByTag(req.query.tag);
  questions.forEach((item) => {
    if (item.question_tags) {
      item.question_tags = item.question_tags.split(',');
    }
    if (item.question_img) {
      item.question_img = item.question_img.split('\\').slice(-1).join('/');
    }
  });
  res.send({
    resCode: 200,
    data: questions,
  });
});

questionRouter.post('/questionReputationUp', (req, res) => {
  if (req.body.id) {
    goodQuestionReputation(req.body.id, 1)
      .then(async () => {
        const question = await queryQuestionById(req.body.id);
        res.send({ resCode: '200', data: question });
      })
      .catch(() => {
        res.send({ resCode: '500', message: '失败' });
      });
  } else {
    res.send({ resCode: '404', message: '找不到数据' });
  }
});

questionRouter.post('/questionReputationDown', (req, res) => {
  badQuestionReputation(req.body.id, 1)
    .then(async () => {
      const question = await queryQuestionById(req.body.id);
      res.send({ resCode: '200', data: question });
    })
    .catch(() => {
      res.send({ resCode: '500', message: '失败' });
    });
});

questionRouter.get('/queryQuestionByDate', (req, res) => {
  let date = req.query.date.split('-');
  if (Number(date[2]) < 10) {
    date[2] = Number(date[2]).toString();
  }
  date = date.join('/');
  queryQuestionByDate(date)
    .then((data) => {
      if (data.length > 0) {
        res.send({
          resCode: 200,
          data,
        });
      } else {
        res.send({
          resCode: 404,
          message: '找不到数据',
        });
      }
    })
    .catch((err) => {
      console.log(err);
    });
});

questionRouter.get('/queryQuestionByDateline', (req, res) => {
  let dateline = req.query.dateline.map((date) => {
    date = date.split('-');
    if (Number(date[2]) < 10) {
      date[2] = Number(date[2]).toString();
    }
    date = date.join('/');
    return date;
  });
  dateline[0] = `${dateline[0]} 00:00:00`;
  dateline[1] = `${dateline[1]} 23:59:59`;
  queryQuestionByDateline(req.query.userId, dateline)
    .then((data) => {
      if (data.length > 0) {
        res.send({
          resCode: 200,
          data,
        });
      } else {
        res.send({
          resCode: 404,
          message: '找不到数据',
        });
      }
    })
    .catch((err) => {
      console.log(err);
    });
});

questionRouter.get('/queryQuestionByUser', (req, res) => {
  queryQuestionByUser(req.query.userId).then((data) => {
    if (data.length > 0) {
      data.forEach((item) => {
        if (item.question_tags) {
          item.question_tags = item.question_tags.split(',');
        }
        if (item.question_img) {
          item.question_img = item.question_img.split('\\').slice(-1).join('/');
        }
      });
      data = data.reverse();
      res.send({
        resCode: 200,
        data,
      });
    } else {
      res.send({
        resCode: 404,
        message: '找不到用户的问题',
      });
    }
  });
});

questionRouter.get('/queryQuestionByUsertag', (req, res) => {
  const { userId, tag } = req.query;
  queryQuesitonByUsertag(userId, tag).then((data) => {
    if (data.length > 0) {
      data.forEach((item) => {
        if (item.question_tags) {
          item.question_tags = item.question_tags.split(',');
        }
        if (item.question_img) {
          item.question_img = item.question_img.split('\\').slice(-1).join('/');
        }
      });
      data = data.reverse();
      res.send({
        resCode: 200,
        data,
      });
    } else {
      res.send({
        resCode: 404,
        message: '找不到用户的问题',
      });
    }
  });
});

questionRouter.get('/queryQuestionById', (req, res) => {
  queryQuestionById(req.query.questionId).then(({ dataValues }) => {
    if (dataValues) {
      res.send({
        resCode: 200,
        data: dataValues,
      });
    }
  });
});

questionRouter.post('/questionViewCountUp', (req, res) => {
  const { question_id } = req.body;
  if (question_id) {
    questionViewCountUp(question_id).then(() => {
      res.send({ resCode: 200, message: '浏览量增加' });
    });
  } else {
    res.send({ resCode: 500, message: '浏览量增加错误' });
  }
});

questionRouter.get('/queryQuestionByKeyword', (req, res) => {
  const { keyword } = req.query;
  if (keyword.replace(/\s+/g, '') === '') {
    res.send({ resCode: 500, message: '无意义的参数' });
  } else {
    queryQuestionByKeyword(keyword).then((data) => {
      if (data.length > 0) {
        for (const item of data) {
          item.question_tags = item.question_tags.split(',');
        }
        res.send({ resCode: 200, data });
      } else {
        res.send({ resCode: 404, message: '找不到数据' });
      }
    });
  }
});

questionRouter.get('/queryHotQuestionByTag', (req, res) => {
  const { tag } = req.query;
  if (tag.replace(/\s+/g, '') === '') {
    res.send({ resCode: 500, message: '无意义的参数' });
  } else {
    queryHotQuestionByTag(tag)
      .then((data) => {
        if (data.length > 0) {
          res.send({ resCode: 200, data });
        } else {
          res.send({ resCode: 404, message: '找不到数据' });
        }
      })
      .catch((err) => {
        res.send({ resCode: 500, message: '查询失败' });
      });
  }
});

questionRouter.post('/editQuestion', (req, res) => {
  const { questionInfo } = req.body;

  editQuestion(questionInfo)
    .then((data) => {
      res.send({ resCode: 200, message: '修改成功' });
    })
    .catch((err) => {
      res.send({ resCode: 500, message: '修改失败' });
    });
});

questionRouter.post('/deleteQuestion', (req, res) => {
  const { question_id } = req.body;

  deleteAnswerBySubordinate(question_id)
    .then(() => {
      deleteQuestion(question_id)
        .then((data) => {
          res.send({ resCode: 200, message: '删除成功' });
        })
        .catch((err) => {
          console.log(err);
          res.send({ resCode: 500, message: '删除失败' });
        });
    })
    .catch((err) => {
      console.log(err);
      res.send({ resCode: 500, message: '删除失败' });
    });
});

export default questionRouter;
